package com.example.financechain.controller;

import com.alibaba.fastjson.JSONArray;
import com.example.financechain.Utils.JsonData;
import com.example.financechain.Utils.UserThreadLocal;
import com.example.financechain.domain.LoginParam;
import com.example.financechain.service.LoginService;
import com.example.financechain.service.IRoleService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@RestController
@RequestMapping("public/Login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    DefaultKaptcha producer;

    @Autowired
    IRoleService iRoleService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 获取验证码
     * @return
     * @throws IOException
     */
    @GetMapping("/captcha")
    public Map<String, Object> captcha() throws IOException {
        return loginService.captchaCreator();
    }

//    @GetMapping("/captcha")
//    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        String text = producer.createText();  // 获取验证码文本内容
//        // 根据文本验证码内容创建图形验证码
//        BufferedImage image = producer.createImage(text);
//        try (ServletOutputStream outputStream = response.getOutputStream()) {
//            // 输出流输出文件格式为jpg
//            ImageIO.write(image, "jpg", outputStream);
//            outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * 登录
     * @param loginParam
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("login")
    public JsonData login(@RequestBody LoginParam loginParam) throws NoSuchAlgorithmException {

        return loginService.login(loginParam);

    }

    /**
     * 登出
     * @return
     */
    @GetMapping("logout")
    public JsonData logout(){

        Long roleId = UserThreadLocal.get().getRoleId();
        stringRedisTemplate.delete(roleId.toString());

        return JsonData.buildSuccess(null,"登出成功");

    }




}
